<?php

namespace app\api\controller;
use think\Db;
/**
 * 用户api接口
 */
class Cron 
{
    /**
     * 获取环信聊天记录
     */
    public function chat_history()
    {
        $list = getChatHistory();
        foreach($list as $value)
        {
           $chat = Db::name('chat')->where('msg_id',$value['msg_id'])->find();
           // 根据 msg_id判断此聊天记录是否存在，如果存在不插入，存在则插入数据库
           if(!$chat)
           {
              $value['payload'] = json_encode($value['payload'],JSON_UNESCAPED_UNICODE);
              Db::name('chat')->insert($value);
              Log::info('聊天记录', $value['msg_id'].'插入成功');
           }
        }
    }

    // 过期的广告下架
    public function ad()
    {
       $adList = Db::name('advertisement')->where(['status'=>'normal'])->select();
       foreach ($adList as $k => $v) {
          if(strtotime($v['endtime']) < time())
          {
             Db::name('advertisement')->where(['id'=>$v['id']])->update(['status'=>'hidden']);
          }
       }
    }

    // 活动结束 分销
    public function distribution()
    {
      $list = model('Travel')->where(['state'=>2])->whereTime('endtime', '<', time())->select();
      foreach ($list as $k => $v) {
         // 活动活动报名人数
          $count = model('TravelMember')->get(['travel_id'=>$v]);

          if($count < $v['group_num'])
          {
             // 未达到成团人数  活动自动取消 退还会员报名费
             $result = model('Travel')->save(['state'=>5],['id'=>$v['id']])
             if($result !== false)
             {
                $travelMembers = model('TravelMember')->where(['travel_id'=>$v['id'],'paid'=>1])->select();
                foreach ($travelMembers as $key => $value) {
                   $order = model('Order')->where(['type'=>1,'good_id'=>$value['id']])->find();
                   action('Pay/refund', ['order_id'=>$order['id']]);
                }
             }
          }
          else
          {
             // 设置活动为已结束 
             if(model('Travel')->save(['state'=>3],['id'=>$v['id']]))
             {
               // 获取发布活动人的信息
                $sponsor = model('User')->get($v['sponsor']);
                //总利润
                $total = $count * $v['memebr_price'] - $v['cost'];

                //计算佣金 总利润的70% * 20% / 最多限制人数
                $commission = ($total * 0.7) * 0.2 / $v['limit_num'];

                // role： 1 社群；2 用户
                switch ($sponsor['role']) {
                  case '1':
                        if($v['type'] == 0)
                        {
                            // 国内活动
                            //1、 转账给供应商
                            $travel = TravelModel::with('activity')->where(['id'=>$travel_id])->find();
                            foreach ($travel['activity'] as $ak => $av) {
                              $supplier = model('supplier')->get($av['supplier_id']);
                              $time = "(".date('Y/m',$av['pivot']['begintime']."-".date('Y/m',$av['pivot']['endtime'].")";
                              $title = "活动名称";
                              if($supplier['type'] == 1)
                              {
                                  $title = "活动场地";
                              }

                              $data = [
                                'travel_id'=>$v['id'],
                                'title'  =>$title,
                                'content'=>$av['name'],
                                'type' => 1,
                                'user_id'=>$supplier['id'],
                                'fee'=>$av['fee'],
                              ];
                              model('TravelDistribution')->save($data);

                              $param = [
                                  'good_id'   => model('TravelDistribution')->id,
                                  'timestamp' => time(),
                                  'total_fee' => $av['fee'],
                                  'title'     => $v['titles'],
                                  'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                                  'type'      => 5,//"ALI_APP";
                                  'bill_no'   => date('Ymdh') . time(),
                              ];
                              $result = model('Order')->allowField(true)->isUpdate(false)->save($param);
                              model('User')->where(['id'=>$supplier['id']])->setInc('sum_income',$av['fee']);
                             /* if($result !== false)
                              {
                                 action('Pay/transfer', ['order_id'=>model('Order')->id]);
                              }*/

                              // 5、退还活动定金
                              $order_id = model('Order')->where(['type'=>4,'good_id'=>$v['id']])->value('id');
                              $data = [
                                'travel_id'=>$v['id'],
                                'title'=>"退还活动定金",
                                'content'=>$av['name'],
                                'type' => 2,
                                'user_id'=>$sponsor['id'],
                                'fee'=>$v['deposit'],
                              ];
                              model('TravelDistribution')->save($data);
                              action('Pay/refund', ['order_id'=>$order_id]);
                            }
                        }
                       
                        // 2、 各个用户的佣金（总利润的70% * 20% / 最多限制人数）
                        $travelMembers = model('TravelMember')->field('parentid,count(*) as num')->group('parentid')->where('parentid','<>',0)->select();
                        $sum_commission = 0;
                        foreach ($travelMembers as $mk => $mv) {
                            $data = [
                            'travel_id'=>$v['id'],
                            'title'=>"支付推广佣金",
                            'content'=>$travel['titles'],
                            'type' => 2,
                            'user_id'=>$mv['parentid'],
                            'fee'=>$commission * $mv['num'],
                          ];
                          model('TravelDistribution')->save($data);
                          $param = [
                                'good_id'   => model('TravelDistribution')->id,
                                'timestamp' => time(),
                                'total_fee' => $commission * $mv['num'],
                                'title'     => $v['titles'].'活动佣金',
                                'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                                'type'      => 6,//"ALI_APP";
                                'bill_no'   => date('Ymdh') . time(),
                            ];
                            $result = model('Order')->allowField(true)->isUpdate(false)->save($param);
                            if($result !== false)
                            {
                               action('Pay/transfer', ['order_id'=>model('Order')->id]);
                            }
                            $sum_commission += $sum_commission;

                            // 用户的电子钱包，总收入增加
                            model('User')->where(['id'=>$mv['parentid']])->setInc('sum_income',$commission * $mv['num']);
                            // 用户的电子钱包，活动收入增加
                            //model('User')->where(['id'=>$mv['parentid']])->setInc('activity_income',$commission * $mv['num']);
                        }

                        // 3、 社群毛利（总利润的70% - 用户佣金）
                        $data = [
                            'travel_id'=>$v['id'],
                            'title'    =>"活动赚取金额",
                            'content'  =>$travel['titles'],
                            'type'     => 2,
                            'user_id'  =>$sponsor['id'],
                            'fee'      =>$total - $sum_commission,
                          ];
                          model('TravelDistribution')->save($data);
                          $param = [
                                'good_id'   => model('TravelDistribution')->id,
                                'timestamp' => time(),
                                'total_fee' => $total - $sum_commission,
                                'title'     => $v['titles'].'活动金额',
                                'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                                'type'      => 6, // "ALI_APP";
                                'bill_no'   => date('Ymdh') . time(),
                            ];
                            $result = model('Order')->allowField(true)->isUpdate(false)->save($param);
                            /*if($result !== false)
                            {
                               action('Pay/transfer', ['order_id'=>model('Order')->id]);
                            }*/
                            // 用户的电子钱包，总收入增加
                            model('User')->where(['id'=>$sponsor['id']])->setInc('sum_income',$total - $sum_commission);
                            // 用户的电子钱包，活动收入增加
                            model('User')->where(['id'=>$sponsor['id']])->setInc('activity_income',$total - $sum_commission);

                        // 4、 平台收取的服务费

                        // 5、 退还活动定金
                    break;
                  default:
                    # 默认用户
                    // 1、转账给供应商
                    // 2、退还活动定金
                  $travel = TravelModel::with('activity')->where(['id'=>$travel_id])->find();
                            foreach ($travel['activity'] as $ak => $av) {
                              $supplier = model('supplier')->get($av['supplier_id']);
                              $time = "(".date('Y/m',$av['pivot']['begintime']."-".date('Y/m',$av['pivot']['endtime'].")";
                              $title = "活动名称";
                              if($supplier['type'] == 1)
                              {
                                  $title = "活动场地";
                              }

                              $data = [
                                'travel_id'=>$v['id'],
                                'title'  =>$title,
                                'content'=>$av['name'],
                                'type' => 1,
                                'user_id'=>$supplier['id'],
                                'fee'=>$av['fee'],
                              ];
                              model('TravelDistribution')->save($data);

                              $param = [
                                  'good_id'   => model('TravelDistribution')->id,
                                  'timestamp' => time(),
                                  'total_fee' => $av['fee'],
                                  'title'     => $v['titles'],
                                  'channel'   => input('channel','ALI_APP'),//"ALI_APP";
                                  'type'      => 5,//"ALI_APP";
                                  'bill_no'   => date('Ymdh') . time(),
                              ];
                              $result = model('Order')->allowField(true)->isUpdate(false)->save($param);
                              model('User')->where(['id'=>$supplier['id']])->setInc('sum_income',$av['fee']);
                              /*if($result !== false)
                              {
                                 action('Pay/transfer', ['order_id'=>model('Order')->id]);
                              }*/

                              // 5、退还活动定金
                              $order_id = model('Order')->where(['type'=>4,'good_id'=>$v['id']])->value('id');
                              $data = [
                                'travel_id'=> $v['id'],
                                'title'    => "退还活动定金",
                                'content'  => $av['name'],
                                'type'     => 2,
                                'user_id'  => $sponsor['id'],
                                'fee'      => $v['deposit'],
                              ];
                              
                              model('TravelDistribution')->save($data);
                              action('Pay/refund', ['order_id'=>$order_id]);
                            }
                    break;
                }
             }
          }
      }
    }
}
